package com.edu.order.controller;
 
import com.alibaba.fastjson.JSON;
import com.edu.api.entity.common.JwtUtil;
import com.edu.api.entity.common.TimeUtil;
import com.edu.order.config.RabbitmqConfig;
import com.edu.order.service.CourseFeign;
import com.edu.order.service.PayOrderRecordService;
import com.edu.order.service.PayOrderService;
import com.edu.order.service.UserCourseOrderService;
import com.github.wxpay.sdk.WXPayUtil;
import com.jfinal.kit.HttpKit;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName ReceiveHandler
 * @Description TODO
 * @Author
 * @Date
 * @Version 1.0
 */
@Component
public class ReceiveHandler {

    @Autowired
    private UserCourseOrderService userCourseOrderService;

    @Autowired
    private PayOrderRecordService payOrderRecordService;

    @Autowired
    CourseFeign courseFeign;

    @Autowired
    private PayOrderService payOrderService;

    private String fromStatus = "CREATE";


    //监听WECHAT_PAY队列
    @RabbitListener(queues = {RabbitmqConfig.QUEUE_INFORM_WECHAT_PAY})
    public void receive_wechat_pay(String message) throws Exception {
        HashMap hashMap = JSON.parseObject(message, HashMap.class);
        String url = (String) hashMap.get("url");
        String xml = (String) hashMap.get("xml");
        String orderId = (String) hashMap.get("orderId");
        String userId = (String) hashMap.get("userId");
        String ip = (String) hashMap.get("ip");
        String courseName = (String) hashMap.get("courseName");
        String productId = (String) hashMap.get("productId");
        //第一次询问时间
        long beginTime = System.currentTimeMillis();
        int index = 0;
        while(true) { //不停的去微信后台询问是否支付
            String result = HttpKit.post(url, xml);
//            System.out.println(result);//报错：<![CDATA[签名错误]]>

            //4.后台返回的xml格式，转成map，并添加两个参数
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);

            //5.将map转成json并返回给浏览器
            //未支付,修改状态继续询问。
            if(resultMap.get("trade_state").equalsIgnoreCase("NOTPAY") && index == 0){
                index++;
                fromStatus=resultMap.get("trade_state");
                userCourseOrderService.updateUserCourseOrder(orderId, (byte) 10);
                payOrderRecordService.addPayOrderRecord(orderId,"NOTPAY","CREATE", userId, resultMap.get("total_fee"));
            }
            //已经成功支付，停止询问
            if(resultMap.get("trade_state").equalsIgnoreCase("success")){
                //支付成功并添加并修改表
                userCourseOrderService.updateUserCourseOrder(orderId, (byte) 20);
                payOrderRecordService.addPayOrderRecord(orderId,"PAY","NOTPAY",userId, resultMap.get("total_fee"));
                payOrderService.insertPayOrder(orderId,Integer.valueOf(userId),
                        Integer.valueOf(productId), courseName,new BigDecimal(resultMap.get("total_fee")),
                        resultMap.get("fee_type"),resultMap.get("trade_type"),(byte)2,ip, TimeUtil.getTimeDate(),resultMap.get("transaction_id"));
                courseFeign.updateSales(productId);
//                return resultMap;
            }
            //超过30秒未支付，停止询问
            if(System.currentTimeMillis() - beginTime > 10000){
                //`去微信撤销订单`
                url = "https://api.mch.weixin.qq.com/pay/closeorder";
                String resultReverse = HttpKit.post(url, xml);
                resultMap = WXPayUtil.xmlToMap(resultReverse);

                userCourseOrderService.updateUserCourseOrder(orderId, (byte) 40);
                payOrderRecordService.addPayOrderRecord(orderId,"OVERDUE",fromStatus,userId,"0");
//                return resultMap;
            }
            Thread.sleep(3000); //每隔3秒，询问一次微信后台
        }
    }
}